package com.autoagent.ai_live_master.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.autoagent.ai_live_master.common.base.ApiResponse;
import com.autoagent.ai_live_master.common.base.UserContext;
import com.autoagent.ai_live_master.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 认证拦截器 - 用于验证用户登录状态
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle....");
        // 1.获取请求的url
        String url = request.getRequestURL().toString();
        log.info("请求的url:{}", url);

        // 2.判断url是否包括login关键字，如果包含就放行
        if (url.contains("login")) {
            log.info("登陆操作,直接放行...");
            return true;
        }
        // 3.如果不是登录请求，那就拦截，获取请求头中的令牌（token）
        String jwt = request.getHeader("token");
        log.info("本次请求携带的jwt:{}", jwt);
        // 4.判断jwt令牌是否存在。不存在返回未登录的错误结果
        if (jwt == null || jwt.isEmpty()) {
            log.info("请求头token为空，返回未登陆的信息");
            ApiResponse error = ApiResponse.error(401, "NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        // 5.解析token，如果解析失败，返回错误结果
        try {
            Claims claims = jwtUtils.parseJWT(jwt);
            // 将解析出的id存储到全局变量中
            Long userId = claims.get("id", Long.class);
            UserContext.setCurrentUserId(userId);
            log.info("解析出的用户ID: {}", userId);
        } catch (Exception e) {
            log.error("解析令牌失败，返回未登陆的错误信息", e);
            ApiResponse error = ApiResponse.error(401, "NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        // 6.放行
        log.info("令牌合法,放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion....");
    }
}


